/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.xs_writer.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.xs_writer.entity.XsWriter;
import com.jeeplus.modules.xs_writer.mapper.XsWriterMapper;
import com.jeeplus.modules.xs_writer.entity.XsWriterIncome;
import com.jeeplus.modules.xs_writer.mapper.XsWriterIncomeMapper;

/**
 * 作家信息Service
 * @author 天竹子
 * @version 2021-07-15
 */
@Service
@Transactional(readOnly = true)
public class XsWriterService extends CrudService<XsWriterMapper, XsWriter> {

	@Autowired
	private XsWriterIncomeMapper xsWriterIncomeMapper;

	public XsWriter get(String id) {
		XsWriter xsWriter = super.get(id);
		xsWriter.setXsWriterIncomeList(xsWriterIncomeMapper.findList(new XsWriterIncome(xsWriter)));
		return xsWriter;
	}

	public List<XsWriter> findList(XsWriter xsWriter) {
		return super.findList(xsWriter);
	}

	public Page<XsWriter> findPage(Page<XsWriter> page, XsWriter xsWriter) {
		return super.findPage(page, xsWriter);
	}

	@Transactional(readOnly = false)
	public void save(XsWriter xsWriter) {
		int i = 0;
		if(StringUtils.isNotBlank(xsWriter.getId())){
			i = 1;
		}
		super.save(xsWriter);
		if(i == 0){
			XsWriterIncome xsWriterIncome = new XsWriterIncome();
			xsWriterIncome.setTotalRevenue(0.0);
			xsWriterIncome.setBounty(0.0);
			xsWriterIncome.setRemuneration(0.0);
			xsWriterIncome.setWriter(xsWriter);
			xsWriterIncomeMapper.insert(xsWriterIncome);
		}
		for (XsWriterIncome xsWriterIncome : xsWriter.getXsWriterIncomeList()){
			if (xsWriterIncome.getId() == null){
				continue;
			}
			if (XsWriterIncome.DEL_FLAG_NORMAL.equals(xsWriterIncome.getDelFlag())){
				if (StringUtils.isBlank(xsWriterIncome.getId())){
					xsWriterIncome.setWriter(xsWriter);
					xsWriterIncome.preInsert();
					xsWriterIncomeMapper.insert(xsWriterIncome);
				}else{
					xsWriterIncome.preUpdate();
					xsWriterIncomeMapper.update(xsWriterIncome);
				}
			}else{
				xsWriterIncomeMapper.delete(xsWriterIncome);
			}
		}
	}

	@Transactional(readOnly = false)
	public void delete(XsWriter xsWriter) {
		super.delete(xsWriter);
		xsWriterIncomeMapper.delete(new XsWriterIncome(xsWriter));
	}

}